import React, {useState, useRef, useEffect} from 'react';
import {message, Button, Divider, Popconfirm} from 'antd';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import {PlusOutlined} from '@ant-design/icons';
import {getShiftList,saveAndUpdateShiftInfo,deleteShift,shiftBpm,getFrequencyList} from '../service';
import moment from 'moment';
import ShiftAddForm from './components/ShiftAddForm';
import { BPMStatusEnum } from "@/utils/constant";

const TableList = () => {
  const actionRef = useRef();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [record, setRecord] = useState(null);
  const [title, setTitle] = useState(null);
  const [rank,setRank] = useState([]);

  useEffect(() => {
    getFrequencyList().then(res => {setRank(res);});
  }, []);

  const addAndEditShift = (record) => {
    if(record){
      setRecord(record);
    }
    setTitle(record ? '编辑' : '申请');
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    setRecord(null);
  };

  const delShift = (id) => {
    setLoading(true);
    deleteShift(id).then(res => {
      if (res.flag) {
        message.success(`删除成功！`);
        actionRef.current.reload();
      } else {
        message.error(`删除失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const sendShiftBpm = (id) => {
    setLoading(true);
    shiftBpm(id).then(res => {
      if (res.flag) {
        message.success(`bpm发起成功！`);
        window.open(res.data);
      } else {
        message.error(`bpm错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveAndUpdateShiftInfo(values).then(res => {
      if (res.flag) {
        handleCancel();
        message.success(`操作保存成功！`);
        actionRef.current.reload();
      } else {
        message.error(`保存失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) =>{
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      }
    },
    {
      title: '调班申请人',
      hideInSearch: true,
      dataIndex: 'shiftName',
    },
    {
      title: '申请人工号',
      dataIndex: 'shiftCode',
      hideInSearch: true,
    },
    {
      title: '被调班人',
      dataIndex: 'beShiftName',
      hideInSearch: true,
    },
    {
      title: '被调班人工号',
      dataIndex: 'beShiftCode',
      hideInSearch: true,
    },
    {
      title: '调班时间',
      dataIndex: 'shiftDate',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '调班班次',
      hideInSearch: true,
      dataIndex: 'frequency',
      render: (text) =>{
        return text!=='-' ? rank.find((item) => item.id === text)?.name : '';
      }
    },
    {
      title: '被调班班次',
      hideInSearch: true,
      dataIndex: 'beFrequency',
      render: (text) =>{
        return text!=='-' ? rank.find((item) => item.id === text)?.name : '';
      }
    },
    {
      title: '审批状态',
      dataIndex: 'approveStatus',
      valueEnum: BPMStatusEnum,
    },
    {
      title: '调班说明',
      dataIndex: 'reason',
      ellipsis:true,
      width: 200
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align:'center',
      render: (item, record) => (
        <>
          {
            (record.approveStatus === 0) && <>
              <a onClick={() => addAndEditShift(record)}>编辑</a>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认删除?`} onConfirm={() => delShift(record.id)} okText="是" cancelText="否">
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical"/>
              <a onClick={() => sendShiftBpm(record.id)}>发起BPM</a>
            </>
          }
          {(record.approveStatus !== 0 && record.bpmUrl) && <><a onClick={() => window.open(record.bpmUrl)}>查看详情</a></>}
        </>
      ),
    }
  ];

  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        request={(params) => getShiftList(params)}
        columns={columns}
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => addAndEditShift(null)}><PlusOutlined/>新增</Button>,
        ]}
      />
      <ShiftAddForm
        loading={loading}
        visible={visible}
        record={record}
        title={title}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};

export default (TableList);
